package com.example.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

// 配置文件 , 返回
/*
* 实现统一数据返回的保底类
* 在返回数据之前检查数据的类型是否为统一的对象
* */
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    /*开关 , 只有TRUE 才会调用beforeBodyWrite*/
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /*对数据格式进行封装和校验*/
    @SneakyThrows //统一异常
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof AjaxResult)return body;
        //instanceof是Java中的二元运算符，左边是对象，右边是类；当对象是右边类或子类所创建对象时，返回true；否则，返回false。
        if (body instanceof String){
            /*转换为JSON*/
            return objectMapper.writeValueAsString(AjaxResult.successs(body));
        }
        return AjaxResult.successs(body);
    }


}
